import { join } from 'path'
import { BrowserWindow, shell, screen } from 'electron'
import icon from '../../resources/icon.png?asset'
import { is } from '@electron-toolkit/utils'

export function createWindow(): void {
  const width = 460
  const height = 670
  const offset = 20

  const { width: windowWidth, height: windowHeight } = screen.getPrimaryDisplay().workAreaSize

  const mainWindow = new BrowserWindow({
    width: width,
    height: height,
    x: windowWidth - width - offset,
    y: windowHeight - height - offset,
    resizable: false,
    frame: false,
    show: false,
    autoHideMenuBar: true,
    alwaysOnTop: is.dev,
    skipTaskbar: is.dev,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  if (is.dev) {
    // f5 刷新
    mainWindow.webContents.on('before-input-event', (event, input) => {
      if (input.key.toLowerCase() === 'f5') {
        mainWindow.reload()
        event.preventDefault()
      }
    })
  }
}
